package com.sfang.common.util.encrypt;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@Component
public class RSAUtil {

    private static Logger LOGGER = LoggerFactory.getLogger(RSAUtil.class);
    private PublicKey publicKey;
    private PrivateKey privateKey;

    @Autowired
    private Environment environment;

    @PostConstruct
    public void init() throws NoSuchAlgorithmException, InvalidKeySpecException {

        try {
            publicKey = KeyFactory.getInstance("RSA")
                    .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(environment.getProperty("authorization.key.public"))));

            privateKey = KeyFactory.getInstance("RSA")
                    .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(environment.getProperty("authorization.key.private"))));

        } catch (Exception e) {

        }
    }

    public static byte[] encrypt(String plainValue, PublicKey publicKey) {
        try {
            Cipher encryptCipher = Cipher.getInstance("RSA");
            encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedBytes = encryptCipher.doFinal(plainValue.getBytes());
            return encryptedBytes;
        } catch (Exception e) {
            LOGGER.error(String.format("RSAUtil encrypt exception,data-【%s】 error-【%s】", plainValue, JSON.toJSONString(e)));
            return null;
        }
    }

    public static byte[] decrypt(byte[] encrypted, PrivateKey privateKey) {
        try {
            Cipher decryptCipher = Cipher.getInstance("RSA");
            decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decryptedBytes = decryptCipher.doFinal(encrypted);
            return decryptedBytes;
        } catch (Exception e) {
            LOGGER.error(String.format("RSAUtil decrypt exception,data-【%s】 error-【%s】", encrypted, JSON.toJSONString(e)));
            return null;
        }
    }
}
